#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import urllib.parse
from typing import Optional
from urllib.parse import parse_qs, urlparse

import requests
from bs4 import BeautifulSoup

baseUrl = "https://dayu.changdu.vip"
redirect_uri: str = f"{baseUrl}/login"
apiUrl = "https://dayu-data-manager.changdu.vip"


class Keycloak:
    """keycloak相关操作"""

    @staticmethod
    def _get_action_url(session: requests.Session) -> str:
        client_id = "dayu"
        url: str = (
            "https://keycloak.changdu.vip/auth/realms/master/protocol/openid-connect/auth?"
            + f"client_id={client_id}&"
            + f"redirect_uri={urllib.parse.quote(redirect_uri)}"
            + "&response_type=code&scope=openid%20profile"
        )

        response = session.get(url, verify=False)

        # 使用BeautifulSoup解析HTML页面
        soup = BeautifulSoup(response.text, "html.parser")

        # 找到form id为"kc-form-login"的元素
        login_form = soup.find("form", id="kc-form-login")

        # 提取form元素的action属性
        if login_form is None:
            print("找不到form.id=kc-form-login")
            return ""

        action_url = login_form.get("action")  # type: ignore
        return str(action_url)

    @staticmethod
    def authenticate(
        session: requests.Session, username: str, password: str
    ) -> Optional[dict]:
        """授权登录, 返回session_state,code"""
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",  # noqa: E501
        }

        data: dict[str, str] = {
            "username": username,
            "password": password,
            "credentialId": "",
        }
        action_url = Keycloak._get_action_url(session)
        response = session.post(
            action_url,
            headers=headers,
            data=data,
            allow_redirects=False,
            verify=False,
        )

        if response.status_code != 302:
            # print(response.text)
            return None

        # 重定向
        location = response.headers["Location"]
        if not location:
            return None

        # 解析URI
        parsed_url = urlparse(location)

        # response = session.get(location, headers=headers, verify=False)

        # 获取参数字典
        query_params = parse_qs(parsed_url.query)

        # 获取特定参数的值
        return {
            "session_state": query_params.get("session_state", [""])[0],
            "code": query_params.get("code", [""])[0],
        }

    # @staticmethod
    # def code(
    #     session: requests.Session,
    #     sessionState: str,
    #     secretKey: str,
    # ) -> Optional[dict]:
    #     """授权码登录"""
    #     headers = {
    #         "accept": "application/json, text/plain, */*",
    #         "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
    #         "Origin": baseUrl,
    #         "Referer": baseUrl + "/",
    #         "Content-Type": "application/json",
    #         "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0",  # noqa: E501
    #     }
    #     data = {
    #         "sessionState": sessionState,
    #         "secretKey": secretKey,
    #         "redirectUri": redirect_uri,
    #     }
    #     url = f"{apiUrl}/api/auth/code"
    #     response = session.post(
    #         url,
    #         headers=headers,
    #         json=data,
    #         verify=False,
    #     )

    #     if response.status_code == 200:
    #         result = response.json()
    #         return result

    #     return None

    # @staticmethod
    # def login(username: str, password: str) -> str:
    #     """登录Keycloak 返回token"""
    #     with requests.Session() as session:
    #         action_url = Keycloak.get_action_url(session)

    #         if not action_url:
    #             print("找不到action_url")
    #             return ""

    #         params = Keycloak.authenticate(session, action_url, username, password)
    #         if params is None:
    #             print_success("Keycloak.authenticate faild!")
    #             return ""

    #     secretKey = params["code"]
    #     session_state = params["session_state"]
    #     accessToken = Keycloak.code(session, session_state, secretKey)
    #     if not accessToken or accessToken["code"] != 200:
    #         print_error("Keycloak.code faild!")
    #         return ""

    #     print_success("Keycloak login succeeded.")
    #     return accessToken["data"]["accessToken"]
